#!/bin/bash
###
 # @Author: didiplus
 # @Description: 文件权限审计与修复模块 v1.0
 # @Date: 2025-06-19 23:21:51
 # @LastEditors: didiplus
 # @LastEditTime: 2025-06-19 23:22:57
 # @FilePath: /script/SecGuardian/modules/audit_perm_fix.sh
 # @Version: 1.0
### 


# 彩色输出封装
print_status() {
    case $1 in
        OK)    echo -e "\e[32m[符合要求]\e[0m $2";;
        FIXED) echo -e "\e[33m[已修复]\e[0m $2 => $3";;
        WARN)  echo -e "\e[31m[异常]\e[0m $2 当前权限: $3 建议: $4";;
        SKIP)  echo -e "\e[34m[跳过]\e[0m $2";;
    esac
}

# 单项检查函数
check_and_fix_permission() {
    local path="$1"
    local expected_perm="$2"
    local description="$3"
    local fix="$4"   # 是否修复（true/false）

    if [[ ! -e "$path" ]]; then
        print_status SKIP "$path 不存在（$description）"
        return
    fi

    actual_perm=$(stat -c "%a" "$path" 2>/dev/null)
    if [[ "$actual_perm" == "$expected_perm" ]]; then
        print_status OK "$path ($description)"
    else
        if [[ "$fix" == "true" ]]; then
            chmod "$expected_perm" "$path"
            print_status FIXED "$path ($description)" "$actual_perm -> $expected_perm"
        else
            print_status WARN "$path ($description)" "$actual_perm" "$expected_perm"
        fi
    fi
}

# 文件权限清单（默认）
default_permission_list=(
    "/etc/passwd:644:账户信息"
    "/etc/shadow:600:账户密码"
    "/etc/group:644:用户组"
    "/etc/gshadow:600:组密码"
    "/etc/ssh/sshd_config:600:SSH配置"
    "/etc/sudoers:440:sudo配置"
    "/etc/crontab:600:计划任务"
    "/etc/fstab:644:挂载配置"
    "/etc/sysctl.conf:644:内核配置"
    "/root:700:root主目录"
    "/boot/grub2/grub.cfg:600:引导配置"
    "/var/log:755:日志目录"
)

# 主函数：传入是否修复和可选文件列表
audit_and_fix_permissions() {
    local fix_mode=${1:-true}  # true 表示修复，false 表示仅审计
    local custom_list=("${@:2}") # 可传入自定义列表

    echo "🔍 开始文件权限${fix_mode:+修复}..."

    local list_to_check=()

    if [[ ${#custom_list[@]} -eq 0 ]]; then
        list_to_check=("${default_permission_list[@]}")
    else
        list_to_check=("${custom_list[@]}")
    fi

    for item in "${list_to_check[@]}"; do
        IFS=':' read -r path perm desc <<< "$item"
        check_and_fix_permission "$path" "$perm" "$desc" "$fix_mode"
    done

    # 特殊处理：日志目录递归权限控制
    if [[ "$fix_mode" == "true" && -d /var/log ]]; then
        find /var/log -type f -exec chmod 640 {} \; 2>/dev/null
        find /var/log -type d -exec chmod 750 {} \; 2>/dev/null
    fi

    echo "✅ 文件权限检查${fix_mode:+及修复}完成。"
}
